#include "static.h"

#include "lualib.h"
#include "lua.h"
#include "lauxlib.h"

#include <string.h>
#include <stdio.h>
#include <memory.h>
#include <stdlib.h>

extern lua_State* g_ufo_lua_state;

static int lua_ufoStaticSetText(lua_State *L)
{
	UFO_View view = *(UFO_View*)luaL_checkudata(L, 1, "ufo.ufoView");
	const char *text = lua_tostring(L, 2);
	
	ufoStaticSetText(view, text);

	return 0;
}

static int lua_ufoStaticSetFont(lua_State *L)
{
	UFO_View view = *(UFO_View*)luaL_checkudata(L, 1, "ufo.ufoView");
	const char *font = lua_tostring(L, 2);

	UFO_Font _font = ufoResourceGetFont(font);
	if (_font) {
		ufoStaticSetFont(view, _font);
		lua_pushinteger(L, 1);
	}

	lua_pushinteger(L, 0);

	return 1;
}

static int lua_ufoStaticSetColor(lua_State *L)
{
	UFO_View view = *(UFO_View*)luaL_checkudata(L, 1, "ufo.ufoView");
	
	int red = lua_tonumber(L, 2);
	int green = lua_tonumber(L, 3);
	int blue = lua_tonumber(L, 4);

	ufoColor color = {red/255.0, green/255.0, blue/255.0, 0};
	ufoStaticSetColor(view, color);
	lua_pushinteger(L, 1);
	return 1;
}

static const struct luaL_Reg staticlib [] = {
	{"setText", lua_ufoStaticSetText},
	{"setColor", lua_ufoStaticSetColor},
	{"setFont", lua_ufoStaticSetFont},
	{0, 0},
};

int internal_initializationScript_static()
{
	if (!g_ufo_lua_state) {
		g_ufo_lua_state = luaL_newstate();
		luaL_openlibs(g_ufo_lua_state);
	}

	luaL_newmetatable(g_ufo_lua_state, "ufo.ufoView");

	lua_pushvalue(g_ufo_lua_state, -1);
	lua_setfield(g_ufo_lua_state, -2, "__index");

	luaL_register(g_ufo_lua_state, 0, staticlib);

	return 1;
}